package com.lenl.datastruct.stack;

import java.util.Scanner;

/**
 * @author Lenl
 * @version v1.0
 * @create 2022-04-29 10:43
 * @description 数组模拟栈
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试一下栈
        //创建初始栈
        ArrayStack arrayStack=new ArrayStack(4);
        String key="";
        boolean loop=true;//控制是否推出菜单
        Scanner scanner=new Scanner(System.in);

        while(loop){
            System.out.println("show: 显示栈");
            System.out.println("exit: 退出程序");
            System.out.println("push 入栈");
            System.out.println("pop 出栈");
            System.out.println("请输入你的选择：");
            key=scanner.next();
            switch (key){
                case "show":
                    arrayStack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数:");
                    int value=scanner.nextInt();
                    arrayStack.push(value);
                    break;
                case "pop":
                    try{
                        int res=arrayStack.pop();
                        System.out.println("出栈的数据为："+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop=false;
                    break;
                default:
                    break;
            }
        }

    }
}

//定义一个ArrayStack标识栈
class  ArrayStack{
    private int maxSize;//栈大小
    private  int[] stack;//数据存储
    private  int top=-1; //栈顶，初始-1
    //构造器
    public ArrayStack(int maxSize){
        this.maxSize=maxSize;
        stack=new int[maxSize];
    }

    //栈满
    public boolean isFull(){
        return top==maxSize-1;
    }
    //栈空
    public  boolean isEmpty(){
        return top==-1;
    }
    //入栈 push
    public void push(int value){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top]=value;
    }
    //出栈 pop
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空，无数据");
        }
        int val=stack[top];
        top--;
        return val;
    }
    //遍历栈
    public void list(){
        //需要从栈顶开始显示数据
        if(isEmpty()){
            System.out.println("栈空，无数据");
            return;
        }
        for(int i=top;i>=0;i--){
            System.out.println("stack["+i+"]="+stack[i]);
        }
    }

}